<?php
/**
 * Created by PhpStorm.
 * User: DR
 * Date: 2018/8/3
 * Time: 14:27
 */

namespace app\common\model;


use think\Model;

class UserRecommend extends Model
{
    //创建顶级用户
    public static function  createFather($user_id)
    {
        $data = [
          'user_id' => $user_id,
            'father_id' => '',
            'son_id'    => '',
            'line_id'   => $user_id
        ];
        self::create($data);
    }

    //创建子用户处理关系表
    public static function createSon($father_id,$son_id)
    {
        $father = self::find(
            [
                'user_id' => $father_id,
            ]
        );
        if(!$father->son_id){
            $father->son_id = $son_id;
        }else{
            $father->son_id = $father->son_id . ',' . $son_id;
        }
        $father->save();
        $data['user_id'] = $son_id;
        $data['line_id'] = $father->line_id;
        if(empty($father->father_id)){
            $data['father_id'] = $father_id;
        }else{
            $data['father_id'] = $father->father_id . ',' . $father_id;
            self::updateUserRelation($father->father_id,$son_id);
        }
        self::create($data);
    }

    //更新用户关系表
    private static function updateUserRelation($father_id,$son_id)
    {
        $map['user_id'] = ['in',$father_id];
        $array = self::where($map)->field('user_id,son_id')->select();
        foreach($array as $key=>$value)
        {
            $son = $value['son_id'] . ',' . $son_id;
            self::where('user_id' , $value['user_id'])->setField('son_id',$son);
        }
    }
}